
var stage2 = new createjs.Stage( "canvas-game" );
var stage = new createjs.Stage( "canvas-start" );
var stage3 = new createjs.Stage( "canvas-end" );

var score;
var scoreText;
var attempts;
var attemptText;
var levelText;
var NUMBER_OF_POLE_LINES = 3;

var initialPositionX = 10;
var initialPositionY = 520;
var initialVelocityX;
var initialVelocityY;

var width = 87;
var width2 = 97;
var height = 87;
var height2 = 75;

var loadingBar;
var progressValue = 0;
var progressText;

var queue;

var manifest = [ { id: "pic1", src: "images/backgrounds.jpg" },
         		{ id: "pic2", src: "images/Butterfly.png" },
         		{ id: "pic3", src: "images/tulip.png" } ];

var LOADING_BAR_WIDTH = 600;
var LOADING_BAR_HEIGHT = 35;

var timestep = 0;
var delta = .3;

var tulipContainers = new Array();
var tulipsImage;
var tulipsContainer;
var numberOfTulips;

var background = new Image();
background.src = "images/backgrounds.jpg";
var backgroundContainer;

var fly = new Image();
fly.src = "images/Butterfly.png";
var flyImage;
var flyContainer;

var audio1 = document.getElementById("gAudio");
var audio3 = document.getElementById("pop");

var game = new Game();
game.resetGame();
game.setLevel( 1 );
game.setGameLevel();

function loadingScreen()
{
	document.getElementById( "velocity" ).style.display = "none";
		
	AudioIntro();
	
	backgroundContainer = new createjs.Bitmap( background );
	backgroundContainer.x = 0;
	backgroundContainer.y = 0;
	
	stage2.addChild( backgroundContainer );
	
	var text = new createjs.Text( "Welcome to Wonderland", "30px Georgia", "red" );
	text.textAlign = "center";
	text.x = 512;
	text.y = 40;
	
	stage2.addChild( text );
	
	var rules = new createjs.Text( "\n \n \n\n Soon wonderland will be covered on white.For that,the butterflies need to collect honey before they migrate to a warmer place.\n " + 
            "\n Can you help them do that by launching the butterflies into the nearest Flower.\n "+
            "\n Type in the appropriate X and Y coordinates to launch The butterflies into the Flowers to collect The honey\n" +
            "\n Keep in mind that you have to launch a certain amount of butterflies in each level and If you dont,GAME OVER!", 
            "15px Georgia-bold", "blue" );
    rules.textAlign = "center";
	rules.x = 512;
	rules.y = 150;
	
	stage2.addChild( rules );
	
	
	var containerPlayButton = new createjs.Container();
	
	var playButton = new createjs.Shape();
	playButton.graphics.setStrokeStyle( "3" );
	playButton.graphics.beginStroke( "purple" );
	playButton.graphics.beginFill( "pink" );
	playButton.graphics.drawRoundRect( 0, 0, 200, 50, 20 );
	
	var playText = new createjs.Text( "Start Butterflies", "20px Georgia", "brown" );
	playText.textAlign = "center";
	playText.x = 200 / 2;
	playText.y = 50 / 3.5;
	
	containerPlayButton.x = 420;
	containerPlayButton.y = 550;
	
	containerPlayButton.addChild( playButton, playText );
	containerPlayButton.addEventListener( "click", playButtonClick );
	
	stage2.addChild( containerPlayButton );
	
	progressText = new createjs.Text( progressValue + "%", "18px Georgia", "brown" );
	progressText.textAlign = "center";
	progressText.x = 900;
	progressText.y = 480;
	
	stage2.addChild( progressText );
	
	var bar = new createjs.Shape();
	bar.graphics.setStrokeStyle( "2" );
	bar.graphics.beginStroke( "brown" );
	bar.graphics.drawRect( 0, 0, LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	
	var barContainer = new createjs.Container();
	barContainer.addChild( bar );
	barContainer.x = stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2;
	barContainer.y = 475;
	
	
	stage2.addChild( barContainer );
	
	loadingBar = new createjs.Shape();
	loadingBar.graphics.beginFill( "green" );
	loadingBar.graphics.drawRect( stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 475, 0, LOADING_BAR_HEIGHT );
	
	stage2.addChild( loadingBar );
	stage2.update();
	
}
function preload()
{
	loadingScreen();
	stage.update();
	
	queue = new createjs.LoadQueue( false );
	
	queue.addEventListener( "fileload", handleFileLoad );
	
	queue.loadManifest( manifest );
	
	queue.load();
}
function handleFileLoad( evt )
{
	var totalProgress = manifest.length;
	
	progressValue = progressValue + 1;
	
	var percentage = Math.ceil( ( progressValue / totalProgress * 100 ) );
	progressText.text = percentage + "% Loaded";
	
	loadingBar.graphics.beginFill( "#00CD66" );
	loadingBar.graphics.drawRect( stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 475, percentage / 100 * LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	stage2.update();
}


function playButtonClick( evt )
{
	document.getElementById( "canvas-start" ).style.display = "inline";
	document.getElementById( "canvas-game" ).style.display = "none";
	init();
}

function init()
{
	stage.removeAllChildren();
	stage.update();
	
	initTulipContainers();
	drawBackground();
	drawGameStats();
	drawPoleAndTulips();
	stage.addChild( flyContainer );
	stage.update();
}
fly.onload = function( evt )
{
	flyImage = new createjs.Bitmap( fly );
	flyImage.shadow = new createjs.Shadow( "black", 5, 5, 5 );
	flyContainer = new createjs.Container();
	flyContainer.x = initialPositionX;
	flyContainer.y = initialPositionY;
	
	var flyShape = new createjs.Shape();
	flyShape.graphics.setStrokeStyle( "1" );
	flyShape.graphics.drawRect( 5, 5, width, height );
	
	flyContainer.addChild( flyImage, flyShape );
	stage.addChild( flyContainer );
	stage.update();
}

function drawBackground()
{
	backgroundContainer = new createjs.Bitmap( background );
	backgroundContainer.x = 0;
	backgroundContainer.y = 0;
	
	stage.addChild( backgroundContainer );
}

function drawGameStats()
{
	scoreText = new createjs.Text( "Score: " + game.getScore(), "18px Georgia", "brown" );
	scoreText.textAlign = "left";
	
	var scoreContainer = new createjs.Container();
	scoreContainer.x = 50;
	scoreContainer.y = 50;
	scoreContainer.addChild( scoreText );
		
	levelText = new createjs.Text( "Level: " + game.getLevel(), "18px Georgia", "brown" );
	levelText.textAlign = "left";
	
	var levelContainer = new createjs.Container();
	levelContainer.x = 50;
	levelContainer.y = 70;
	levelContainer.addChild( levelText );
	
	attemptText = new createjs.Text( "Attempts: " + game.getAttempts(), "18px Georgia", "brown" );
	attemptText.textAlign = "left";
	
	var attemptContainer = new createjs.Container();
	attemptContainer.x = 130;
	attemptContainer.y = 70;
	attemptContainer.addChild( attemptText );
	
	var formBox = new createjs.DOMElement( "velocity" );
	document.getElementById( "velocity" ).style.display = "inline";
	formBox.x = 50;
	formBox.y = 110;
	
	stage.addChild( scoreContainer, levelContainer, attemptContainer, formBox );
}

function initTulipContainers()
{
	document.getElementById( "sAudio" ).play();
	
	numberOfTulips = game.getNumberOfTulips();
	var startingX = 450;
	
	var intervalX = Math.floor( (stage.canvas.width - startingX ) / NUMBER_OF_POLE_LINES - 75 );
	
	for( i = 0; i < numberOfTulips; i = i + 1 )
		{
			
			var tulips = new Image();
			tulips.src = "images/tulip.png";
			tulipsImage = new createjs.Bitmap( tulips );
			tulipsContainer = new createjs.Container();
			tulipsContainer.x = startingX + intervalX * i - 50 + 7.5;
			tulipsContainer.y = game.getTulipHeights()[ i ];
            
			var tulipsShape = new createjs.Shape();
			tulipsShape.graphics.setStrokeStyle( "1" );
			tulipsShape.graphics.drawRect( 0, 0, width2, height2 );
			
			tulipsContainer.addChild( tulipsImage, tulipsShape);
			tulipContainers.push( tulipsContainer );
		}	
}


function drawPoleAndTulips()
{
	numberOfTulips = game.getNumberOfTulips();
	var startingX = 450;
	
	var intervalX = Math.floor( (stage.canvas.width - startingX ) / NUMBER_OF_POLE_LINES - 75 );
	
	for( i = 0; i < numberOfTulips; i = i + 1 )
		{
			if( game.getTulipHeights()[ i ] != -1 )
				{
					
					var pole = new createjs.Shape();
					pole.graphics.beginLinearGradientFill( [ "green", "#4ECA42", "green" ], [ 0, .5, 1 ], startingX + intervalX * i, 0, startingX + intervalX * i + 10, 0 );
					pole.graphics.drawRect( startingX + intervalX * i, 0, 14, stage.canvas.height );
					
					stage.addChild( pole );
					
					
					var tulips = new Image();
					tulips.src = "images/tulip.png";
					tulipsImage = new createjs.Bitmap( tulips );
					tulipsContainer = new createjs.Bitmap( tulips );
					tulipsContainer = new createjs.Container();
					tulipsContainer.x = startingX + intervalX * i - 50 + 7.5;
					tulipsContainer.y = game.getTulipHeights()[ i ];
					
					var tulipsShape = new createjs.Shape();
					tulipsShape.graphics.setStrokeStyle( "1" );
					tulipsShape.graphics.drawRect( 5, 5, width2, height2 );
					
					tulipsContainer.addChild( tulipsImage, tulipsShape );
					
					stage.addChild( tulipsContainer );
				}
		}
	stage.update();
}

function redraw()
{
	stage.removeAllChildren();
	stage.update();
	drawBackground();
	drawGameStats();
	drawPoleAndTulips();
	stage.addChild( flyContainer );
	stage.update();
}

createjs.Ticker.setFPS( 24 );
function tick()
{
	
	initialVelocityX = document.getElementById( "valueX" ).value;
	initialVelocityY = document.getElementById( "valueY" ).value;
	
	flyContainer.x = initialPositionX + initialVelocityX * timestep;
	flyContainer.y = initialPositionY + initialVelocityY * timestep + .5 * 9.81 * timestep * timestep;
	
	timestep = timestep + delta;
	
	
	if( isIntersect() )
	{
		var score = game.getScore();
		game.setScore( score + TULIP_POINTS );
		scoreText.text = "Score: " + game.getScore();
	}
	
  redraw();
		
	if( flyContainer.y > stage.canvas.height || flyContainer.x > stage.canvas.width )
		{
			createjs.Ticker.removeListener( this );
			document.getElementById( "miss" ).play();
			flyContainer.x = initialPositionX;
			flyContainer.y = initialPositionY;
			timestep = 0;
		}
	stage.update();
}
var tulipNumber;
var currentTulip;
function isIntersect()
{
	tulipNumber = tulipContainers.length - 1;
		
	for( var i = tulipNumber; i >= 0; i = i - 1 )
		{
			currentTulip = tulipContainers[ i ];
			if( flyContainer.x < tulipContainers[ i ].x + width2 &&
					flyContainer.x + width > tulipContainers[ i ].x &&
					flyContainer.y < tulipContainers[ i ].y + height2 &&
					flyContainer.y + height > tulipContainers[ i ].y )
				{
					stage.removeChild( currentTulip );
					tulipContainers.splice( i, 1 );
					document.getElementById( "hit" ).play();
					console.log( game.getNumberOfTulips() + "," + tulipNumber );
					
					stage.update();
					
					var levelNumber = game.getLevel();
					if( tulipNumber == 0 )
						{
						    score = game.getScore();
						    numberOfAttempts = game.getAttempts();
						    game.setScore( score + ( numberOfAttempts * ATTEMPT_BONUS_POINTS ) );
						    scoreText.text = "Score: " + game.getScore();
						    
						
							game.setLevel( levelNumber + 1);
							game.setGameLevel();
							game.checkGameStatus();
							stage.removeAllChildren();
							stage.update();
							initTulipContainers();
							drawPoleAndTulips();
							createjs.Ticker.removeListener( this );
							flyContainer.x = initialPositionX;
							flyContainer.y = initialPositionY;
							timestep = 0;
						}
					return true;
				}
			tulipNumber = tulipContainers.length - 1;
		}	
	return false;
}

function launch()
{
	AudioClick()
	
	numberOfAttempts = game.getAttempts();
	if( numberOfAttempts > 0 )
		{
			game.setAttempts( numberOfAttempts - 1 );
			attemptText.text = "Attempts: " + game.getAttempts();
			createjs.Ticker.addListener( this );
		}
	else 
		{
			createjs.Ticker.removeListener( this );
			game.checkGameStatus();
		}
	stage.update();
}


function drawLoserCanvas()
{
	stage3.removeAllChildren();
	stage3.update();
	document.getElementById( "gameover" ).play();
	document.getElementById( "velocity" ).style.display = "none";
	document.getElementById( "canvas-end" ).style.display = "inline";
	document.getElementById( "canvas-start" ).style.display = "none";
		
	backgroundContainer;
	
	var endLText = new createjs.Text( "Oh No, No more butterflies!\n\n", "40px Georgia", "red" );
	endLText.text += "Game Over!!";
	endLText.textAlign = "center";
	endLText.x = 512;
	endLText.y = 200;
	
	stage3.addChild( backgroundContainer, endLText );
	stage3.update();	
}

function drawWinnerCanvas()
{
	stage3.removeAllChildren();
	stage3.update();
	document.getElementById( "winner" ).play();
	document.getElementById( "velocity" ).style.display = "none";
	document.getElementById( "canvas-end" ).style.display = "inline";
	document.getElementById( "canvas-start" ).style.display = "none";
	
		
	backgroundContainer;
	
	var endWText = new createjs.Text( "Yahooo, You did it.You helped the butterflies!\n\n", "40px Georgia", "red" );
	endWText.text += "Thank you";
	endWText.textAlign = "center";
	endWText.x = 512;
	endWText.y = 200;
	
	stage3.addChild( backgroundContainer, endWText );
	stage3.update();	
}


function AudioIntro()
{
	audio1.play();
	audio1.autoplay = true;
	audio1.loop = false;
}


function AudioClick()
{
	audio3.play();
}

//in collaboration with Kara and Amber
